
const addBtn = document.getElementById("add");


addBtn.addEventListener("click", function () {
    addNewNote();
});


function addNewNote(text = "") {
    
    const note = document.createElement("div");
    note.classList.add("note");

    
    note.innerHTML = `
        <div class="tools">
            <button class="edit"><i class="fas fa-edit"></i></button>
            <button class="delete"><i class="fas fa-trash-alt"></i></button>
        </div>
        <div class="main ${text? "": "hidden"}"></div>
        <textarea class="${text? "hidden": ""}"></textarea>
    `;

   
    document.body.appendChild(note);

    
    const deleteBtn = note.querySelector(".delete");
    const editBtn = note.querySelector(".edit");
    const textarea = note.querySelector("textarea");
    const main = note.querySelector(".main");

    
    deleteBtn.addEventListener("click", function () {
        note.remove();
        updateLS();
    });

    editBtn.addEventListener("click", function () {
        textarea.classList.toggle("hidden");
        main.classList.toggle("hidden");
    });

    
    textarea.addEventListener("input", function (e) {
        const { value } = e.target;
        main.innerHTML = marked(value);
        updateLS();
    });

   
    textarea.value = text;
    main.innerHTML = marked(text);
}


function updateLS() {
    
    const textareas = document.querySelectorAll("textarea");
    const notes = [];

    
    textareas.forEach(function (textarea) {
        notes.push(textarea.value);
    });

    
    localStorage.setItem("notes", JSON.stringify(notes));
}


const storedNotes = JSON.parse(localStorage.getItem("notes"));
if (storedNotes) {
    
    storedNotes.forEach(function (noteText) {
        addNewNote(noteText);
    });
}    